package com.controller.dealer;

import com.common.anntation.Log;
import com.common.emums.BusinessType;
import com.common.utils.*;
import com.core.springSecurity.common.SecurityUtils;
import com.core.springSecurity.model.LoginUserDetails;
import com.github.pagehelper.PageInfo;
import com.model.base.PageResult;
import com.model.base.Result;
import com.model.domain.dealer.GetDealerInfoDO;
import com.model.domain.user.GetUserInfoDO;
import com.model.dto.dealer.dealerInfo.DeleteDealerInfoDTO;
import com.model.dto.dealer.dealerInfo.GetDealerListDTO;
import com.model.dto.dealer.dealerInfo.SaveDealerInfoDTO;
import com.model.dto.device.devicePCBInfo.GetDeviceListDTO;
import com.model.dto.machine.machineInfo.DeleteMachineInfoDTO;
import com.model.pojo.dealer.DealerInfo;
import com.model.pojo.device.DeviceObdBaseInfo;
import com.model.pojo.machine.MachineInfo;
import com.model.pojo.sys.SysUser;
import com.model.pojo.user.UserInfo;
import com.model.vo.dealer.dealerInfo.GetDealerListVO;
import com.model.vo.device.deviceOBDInfo.getDeviceList.GetDeviceListVO;
import com.service.dealer.DealerInfoService;
import com.service.sys.SysUserService;
import com.service.user.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.enums.WxMpApiUrl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Description
 * @Author tm
 * @Date 2023-08-26 1:19
 **/
@Api(tags = {"经销商管理"})
@Slf4j
@RestController
@RequestMapping("/v1/dealer")
@RequiredArgsConstructor
public class DealerInfoController {
    private final DealerInfoService dealerInfoService;
    private final SysUserService sysUserService;
    private final UserInfoService userInfoService;

    @Log(title = "经销商管理-经销商列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "经销商列表")
    @PostMapping("/getDealerList")
    public Result<PageResult<List<GetDealerListVO>>> getDealerList(@RequestBody @Valid GetDealerListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        sysUser = sysUserService.get(sysUser.getSysUserId());
        List<GetDealerListVO> voList = new ArrayList<>();
        GetDealerInfoDO getDealerInfoDO = EntityConversionUtil.copy(dto, GetDealerInfoDO.class);
        getDealerInfoDO.setSortRow("createTime");
        if ((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2) && !"testadmin".equals(sysUser.getName()) && sysUser.getUserId() != null) {
            getDealerInfoDO.setFactoryUserId(sysUser.getUserId());
        }
        if (dto.getFactoryId() != null && dto.getFactoryId() != 0) {
            getDealerInfoDO.setFactoryUserId(dto.getFactoryId());
        }
        //农机院播种机
        if ((dto.getFactoryId() == null || dto.getFactoryId() == 0) && (sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机查看权限)) {
            List<Long> factoryUserIds = new ArrayList<>();
            factoryUserIds.add(0l);
            GetUserInfoDO getUserInfoDO = new GetUserInfoDO();
            getUserInfoDO.setUserType(1);
            getUserInfoDO.setDeviceType(3);
            getUserInfoDO.setSortRow("id");
            List<UserInfo> userList = userInfoService.getAllList(getUserInfoDO);
            if (userList != null && userList.size() > 0) {
                factoryUserIds = userList.stream().map(UserInfo::getId).collect(Collectors.toList());
            }
            getDealerInfoDO.setFactoryUserIds(factoryUserIds);
        }

        //播种机厂家
        if(sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机生产厂家){
            getDealerInfoDO.setFactoryUserId(sysUser.getUserId());
        }
        List<DealerInfo> dealerList = dealerInfoService.getPageList(getDealerInfoDO);
        if (dealerList != null && dealerList.size() > 0) {
            dealerList.forEach(item -> {
                GetDealerListVO vo = EntityConversionUtil.copy(item, GetDealerListVO.class);
                vo.setSoldCount(0);//已销售数量
                vo.setUnSoldCount(0);//未销售数量
                String factoryName = "";
                if (item.getSupplierUserId() != null && item.getSupplierUserId() != 0) {
                    UserInfo userInfo = userInfoService.getById(item.getSupplierUserId());
                    if (userInfo != null) {
                        factoryName = userInfo.getName();
                    }
                }
                vo.setFactoryName(factoryName);
                voList.add(vo);
            });
        }
        PageInfo<DealerInfo> pageInfo = new PageInfo<>(dealerList);
        PageResult<List<GetDealerListVO>> build = PageResult.<List<GetDealerListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "经销商管理-添加和修改经销商信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "添加和修改经销商信息")
    @PostMapping("/saveDealerInfo")
    public Result<Objects> saveDealerInfo(@RequestBody @Valid SaveDealerInfoDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        int deviceType = 0;
        sysUser = sysUserService.get(sysUser.getSysUserId());
        if (sysUser.getUserType() == 1 || "testadmin".equals(sysUser.getName()) || sysUser.getUserId() == null) {
            return Result.fail("9999", "当前帐号不能创建经销商");
        }
        if (sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机生产厂家) {
            deviceType = 3;
        }
        boolean flag = false;

        //查询当前经锁商有没有创建帐号
        UserInfo userInfo = userInfoService.getByCellphone(dto.getDealerPhone());
        if (userInfo != null){
            userInfo.setName(dto.getDealerName());
            String password = dto.getPassword();//dto.getDealerPhone().substring(dto.getDealerPhone().length() - 6, dto.getDealerPhone().length());
            userInfo.setPassword(MD5.encode(password, "utf-8"));
            userInfo.setCellphone(dto.getDealerPhone());
            userInfoService.update(userInfo);
            flag = true;
        }else {
            userInfo = new UserInfo();
            userInfo.setName(dto.getDealerName());
            String password = dto.getPassword();//dto.getDealerPhone().substring(dto.getDealerPhone().length() - 6, dto.getDealerPhone().length());
            userInfo.setPassword(MD5.encode(password, "utf-8"));
            userInfo.setCellphone(dto.getDealerPhone());
            userInfo.setUserType(2);
            userInfo.setAllowSecondSupply(0);
            userInfo.setCompanyName("");
            userInfo.setCompanyCode("");
            userInfo.setLicenseUrl("");
            userInfo.setFileUrls("");
            userInfo.setForwardAccount("");
            userInfo.setForwardPwd("");
            userInfo.setDeviceType(deviceType);
            userInfo = userInfoService.save(userInfo);
            flag = true;
        }
        if (flag) {
            int num = 0;
            if (dto.getId() != null && dto.getId() > 0) {
                DealerInfo info = dealerInfoService.findById(dto.getId());
                if (info == null) {
                    return Result.fail("9999", "经销商不存在");
                }
                info.setDealerName(dto.getDealerName());
                info.setDealerPhone(dto.getDealerPhone());
                info.setSupplierUserId(sysUser.getUserId());
                num = dealerInfoService.update(info, dto.getPassword());
            } else {
                DealerInfo info = new DealerInfo();
                info.setDealerName(dto.getDealerName());
                info.setDealerPhone(dto.getDealerPhone());
                info.setSupplierUserId(sysUser.getUserId());
                num = dealerInfoService.save(info, dto.getPassword());
            }
            if (num > 0) {
                if (num > 0) {
                    SysUser sysUser1 = sysUserService.getByMobile(dto.getDealerPhone());
                    if (sysUser1 == null) {
                        sysUser = new SysUser();
                        sysUser.setUserId(userInfo.getId());
                        sysUser.setSysDeptId(1l);
                        sysUser.setName(userInfo.getName());
                        sysUser.setMobile(userInfo.getCellphone());
                        sysUser.setFullName(userInfo.getName());
                        sysUser.setPassword(PasswordUtils.encode(Md5Utils.toUpperCase32(dto.getPassword())));
                        sysUser.setStatus(1);
                        if (deviceType == 1) {
                            sysUser.setUserType((byte) Constants.SysUserUserType.TYPE_TBOX经销商);
                        } else if (deviceType == 3) {
                            sysUser.setUserType((byte) Constants.SysUserUserType.TYPE_播种机经销商);
                        }
                        sysUserService.create(sysUser);
                    } else {
                        sysUser.setUserId(userInfo.getId());
                        sysUser.setSysDeptId(1l);
                        sysUser.setName(userInfo.getName());
                        sysUser.setMobile(userInfo.getCellphone());
                        sysUser.setFullName(userInfo.getName());
                        sysUser.setPassword(PasswordUtils.encode(Md5Utils.toUpperCase32(dto.getPassword())));
                        sysUser.setStatus(1);
                        if (deviceType == 1) {
                            sysUser.setUserType((byte) Constants.SysUserUserType.TYPE_TBOX经销商);
                        } else if (deviceType == 3) {
                            sysUser.setUserType((byte) Constants.SysUserUserType.TYPE_播种机经销商);
                        }
                        sysUserService.update(sysUser);
                    }
                }
            }
        }
        return Result.suc();
    }

    @Log(title = "经销商管理-刪除经销商信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "刪除经销商信息")
    @PostMapping("/deleteDealerInfo")
    public Result<Objects> deleteDealerInfo(@RequestBody @Valid DeleteDealerInfoDTO dto) {
        DealerInfo info = dealerInfoService.findById(dto.getId());
        if (info == null) {
            return Result.fail("9999", "经销商不存在");
        }
        dealerInfoService.delete(info);
        return Result.suc();
    }
}
